import { loginAPI } from '../../api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { constantRoutes, resetRouter } from '@/router'
import { Message } from 'element-ui'
import { getUserInfoAPI } from '@/api/user'

const state = {
  // 1. 从本地取token , 防止刷新token丢失
  token: getToken(),
  userInfo: {},
  // 2. 定义路由数据
  routes: constantRoutes
}

const mutations = {
  // 2. 定义mutations
  saveToken(state, payload) {
    state.token = payload
  },
  removeToken(state) {
    state.token = ''
    removeToken()
    resetRouter()
  },
  saveUserInfo(state, payload) {
    state.userInfo = payload
  },
  setRoutes(state, payload) {
    state.routes = [...constantRoutes, ...payload]
  }
}

const actions = {
  // 2. 定义action函数
  async loginAction(store, payload) {
    // 5. action调用接口 - CORS 跨域访问了

    const res = await loginAPI(payload)

    // 3. 提交修改数据到mutation中
    store.commit('saveToken', res)
    //  store.commit('saveToken', res.data.data)
    // 4. 存token到本地存储
    setToken(res)
    // 5. 跳转到首页
    router.push('/')

    // 6. 提示用户
    Message({
      message: '登录成功',
      type: 'success'
    })
  },
  async getUserInfoAction(store) {
    const res = await getUserInfoAPI()
    store.commit('saveUserInfo', res)
  },
  logoutAction(store) {
    store.commit('saveToken', '') // 清空vuex中token
    removeToken() // 清空cookie中的token
    store.commit('saveUserInfo', {}) // 清空vuex中userInfo
    router.push('/login') // 跳转到登录
    // 重置路由
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
